﻿using System.Collections.Generic;
using Orchard.ContentManagement;
using Orchard.ContentManagement.MetaData;
using Orchard.ContentManagement.MetaData.Builders;
using Orchard.ContentManagement.MetaData.Models;
using Orchard.ContentManagement.ViewModels;
using Contrib.Taxonomies.Models;
using Contrib.Taxonomies.Services;

namespace Mod.NextPreviousItem.Settings
{
    public class NextPreviousTypePartSettings
    {
        public IEnumerable<TaxonomyPart> Taxonomies { get; set; }
        public string Taxonomy { get; set; }


        private bool? _pub;
        public bool Pub
        {
            get
            {
                if (_pub == null)
                    _pub = false;
                return (bool)_pub;
            }
            set
            {
                _pub = value;
            }
        }

        private bool? _wrap;
        public bool Wrap { get
            {
                if (_wrap == null)
                    _wrap = false;
                return (bool)_wrap;
            }
            set
            {
                _wrap = value;
            }
        }            
    }

    public class ContainerSettingsHooks : ContentDefinitionEditorEventsBase
    {
        private readonly ITaxonomyService _taxonomyService;

        public ContainerSettingsHooks(ITaxonomyService taxonomyService)
        {
            _taxonomyService = taxonomyService;
        }

        public override IEnumerable<TemplateViewModel> TypePartEditor(ContentTypePartDefinition definition)
        {
            if (definition.PartDefinition.Name != "NextPreviousItemPart")
                yield break;

            var model = definition.Settings.GetModel<NextPreviousTypePartSettings>();
            model.Taxonomies = _taxonomyService.GetTaxonomies();

            yield return DefinitionTemplate(model);
        }

        public override IEnumerable<TemplateViewModel> TypePartEditorUpdate(ContentTypePartDefinitionBuilder builder, IUpdateModel updateModel)
        {
            if (builder.Name != "NextPreviousItemPart")
                yield break;

            var model = new NextPreviousTypePartSettings();
            updateModel.TryUpdateModel(model, "NextPreviousTypePartSettings", null, null);
            builder.WithSetting("NextPreviousTypePartSettings.Taxonomy", model.Taxonomy);
            builder.WithSetting("NextPreviousTypePartSettings.Pub", model.Pub.ToString());
            builder.WithSetting("NextPreviousTypePartSettings.Wrap", model.Wrap.ToString());

            yield return DefinitionTemplate(model);
        }
    }
}